//
//  AppDelegate.m
//  LoveDraw
//
//  Created by 梁晨 on 2017/6/12.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "AppDelegate.h"
#import "NSString+MD5Addition.h"
#import "RootViewViewController.h"
#import "LoginViewController.h"
#import "sys/utsname.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#import "MainViewController.h"

#import "AdvDetailViewController.h" // 校园公告详情
#import "TeacherMessageListViewController.h"// 教师留言
#import "MessageListViewController.h" // 家长留言
#import "GrowthRecordViewController.h" // 成长记录
#import "RecordViewController.h" // 点名记录
#import "LessonDetailViewController.h"// 课程详情
#import "HoildayViewController.h"
#import "TeacherHoildayViewController.h"
#import <IQKeyboardManager.h>
#import "AdVViewController.h"



#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)nowWindow
{
    return UIInterfaceOrientationMaskPortrait;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    application.applicationIconBadgeNumber = 0;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    // 获取版本
    [self getgain];

    AdVViewController *VC = [[AdVViewController alloc]init];
    self.window.rootViewController = VC;
    
    [self postDevice];
    [self AutoLogin];
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    // Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
//    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];

    [JPUSHService setBadge:0];

    return YES;
}



-(void)AutoLogin
{
    if (![[NSUserDefaults standardUserDefaults]objectForKey:kUserId])
    {

    }else
    {
        [RequestManager RequstWithUrl:@"/index.php?g=App&m=Login&a=accesslogin" parmDic:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} requestType:RequestPOST Success:^(id data)
         {
             UserInfo *userinfo = [UserInfo mj_objectWithKeyValues:data];

             [UserInfoManage sharedInstance].userInfo = userinfo;

             NSSet *set = [NSSet setWithObjects:[NSString stringWithFormat:@"s_%@",[UserInfoManage sharedInstance].userInfo.suid],[NSString stringWithFormat:@"m_%@",[UserInfoManage sharedInstance].userInfo.maid], nil];

             [JPUSHService setAlias:[UserInfoManage sharedInstance].userInfo.uid callbackSelector:nil object:nil];

             [JPUSHService addTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                 
             } seq:0];

         } error:^(NSError *error) {
             
         }];
    }

}

-(void)getgain
{
    NSString *version =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"version"] || ![[[NSUserDefaults standardUserDefaults]objectForKey:@"version"]isEqualToString:version])
    {
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"First"];
    }
    else
    {
         [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"First"];
    }
    [[NSUserDefaults standardUserDefaults]setObject:version forKey:@"version"];
}

// 发送设备信息
-(void)postDevice
{
    // 约定的token
      NSString *verify=[[NSString stringWithFormat:@"%@%@",@"ihuayuanapp",[DeviceInfo getUUid]] stringFromMD5];
    // 系统的名称
    NSString *system_name = @"iOS";
    //系统版本
    NSString *system_version = [[UIDevice currentDevice]systemVersion];
    // 设备型号
    NSString *device_model = [self deviceVersion];
    // 设备用户
    NSString *device_user = [UIDevice currentDevice].name;;
    // UUID
    NSString *UUID = [DeviceInfo getUUid];
    // 纬度
    NSString *latitude = @"";
    // 经度
    NSString *longitude = @"";
    // 类型: 1家长端 2点名ipad端
    NSString *type = @"1";
    //app版本
    NSString *version =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    NSMutableDictionary *ParmDic = [NSMutableDictionary dictionary];
    [ParmDic setValue:verify forKey:@"verify"];
    [ParmDic setValue:system_name forKey:@"system_name"];
    [ParmDic setValue:system_version forKey:@"system_version"];
    [ParmDic setValue:device_model forKey:@"device_model"];
    [ParmDic setValue:device_user forKey:@"device_user"];
    [ParmDic setValue:UUID forKey:@"UUID"];
    [ParmDic setValue:latitude forKey:@"latitude"];
    [ParmDic setValue:longitude forKey:@"longitude"];
    [ParmDic setValue:type forKey:@"type"];
    [ParmDic setValue:version forKey:@"version"];

    NSLog(@"%@",ParmDic);


    [RequestManager NormalRequstWithUrl:@"/index.php?g=App&m=Login&a=verifyDevice_info" parmDic:ParmDic requestType:RequestPOST Success:^(id data)
    {

    } error:^(NSError *error)
    {

    }];

}

// 获取设备号
- (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone7";
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone7Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    return deviceString;
}


#pragma mark --- 极光推送部分

/**
 注册APNs成功并上报DeviceToken

 @param application <#application description#>
 @param deviceToken <#deviceToken description#>
 */
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

/**
 实现注册APNs失败接口（可选）

 @param application <#application description#>
 @param error <#error description#>
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


//添加处理APNs通知回调方法
//请在AppDelegate.m实现该回调方法并添加回调方法中的代码


#pragma mark --- 收到推送的处理

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionSound); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置

    NSLog(@"%@",userInfo);
    [self postInfo:userInfo];


}



// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法

    NSLog(@"info123=====%@",userInfo);

    [self postInfo:userInfo];
//    [self NormalPushVC:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
    

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark ----收到推送的处理
-(void)postInfo:(NSDictionary *)useinfo
{
    NSDictionary *apsDic = useinfo[@"aps"];

    UIAlertController *PushVC = [UIAlertController alertControllerWithTitle:@"消息提示框" message:apsDic[@"alert"] preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"关闭" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *commit = [UIAlertAction actionWithTitle:@"查看" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
    {
        if ([ self.window.rootViewController isKindOfClass:NSClassFromString(@"RootViewViewController")])
        {
            RootViewViewController *VC = (RootViewViewController *)self.window.rootViewController;
            MainViewController *MainVC =  [VC.myNaviVC.viewControllers firstObject];
            [self PushVCFromeVC:MainVC infoDic:useinfo];
        }else
        {
        }
    }];
    [PushVC addAction:cancel];

    [PushVC addAction:commit];

    [self.window.rootViewController presentViewController:PushVC animated:YES completion:nil];
    
}


-(void)PushVCFromeVC:(UIViewController *)FromVCTo infoDic:(NSDictionary* )infoDic
{

    NSInteger index = [infoDic[@"type"] integerValue];

    UINavigationController *navi = FromVCTo.navigationController;

    UIViewController *VC;

    if (index == 1)
    {
        // 公告推送
        AdvDetailViewController *Adv = [[AdvDetailViewController alloc]init];
        Adv.aid = infoDic[@"txt"];
        VC = Adv;
    }else if (index == 3)
    {

        // 老师留言
        TeacherMessageListViewController *teacherList = [[TeacherMessageListViewController alloc]init];
        teacherList.sid = infoDic[@"txt"];
        
        VC = teacherList;
    }else if (index == 2)
    {

        // 家长留言
        MessageListViewController *Messgelist = [[MessageListViewController alloc]init];
        Messgelist.caid = infoDic[@"txt"];
        VC = Messgelist;

    }else if (index == 4)
    {
        // 学习小结
        [RequestManager RequstWithUrl:@"/index.php?g=App&m=StudentCourse&a=index" parmDic:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} requestType:RequestGET Success:^(id data)
         {
             NSArray *dataArr = data;
             for (NSDictionary *lessonDic in dataArr)
             {
                 if ([lessonDic[@"aid"]isEqualToString:infoDic[@"txt"]])
                 {
                     LessonDetailViewController *VC = [[LessonDetailViewController alloc]init];
                     VC.sid = lessonDic[@"aid"];
                     VC.cid = lessonDic[@"cid"];
                     VC.catethumb = lessonDic[@"catethumb"];
                     VC.teachername = lessonDic[@"teachername"];
                     VC.coursename = lessonDic[@"coursename"];
                     [navi pushViewController:VC animated:YES];
                 }
             }

         } error:^(NSError *error) {
             
         }];

        return;

    }else if (index == 5)
    {
        // 成长记录
        GrowthRecordViewController *GrowthVC = [[GrowthRecordViewController alloc]init];
        GrowthVC.sid = infoDic[@"txt"];
        VC = GrowthVC;
    }else if (index == 6)
    {
        // 上课通知
        [navi popToRootViewControllerAnimated:YES];
        return;

    }else if (index == 7)
    {
        // 课费通知
        [navi popToRootViewControllerAnimated:YES];
        return;

    }else if (index == 8)
    {
        //课时到期
        [navi popToRootViewControllerAnimated:YES];
        return;

    }else if (index == 9)
    {
        // 老师上课
        [navi popToRootViewControllerAnimated:YES];
        return;
        
    }else if (index == 11)
    {
        // 点名通知
        RecordViewController *RecordVC = [[RecordViewController alloc]init];
        RecordVC.aid = infoDic[@"txt"];
        VC =  RecordVC;
    }else if(index == 12)
    {
        HoildayViewController *hoildayVC = [[HoildayViewController alloc]init];
        VC = hoildayVC;
    }else if (index == 13)
    {
        TeacherHoildayViewController *TeaHoilday = [[TeacherHoildayViewController alloc]init];
        VC = TeaHoilday;
    }
    

    [navi pushViewController:VC animated:YES];
}


@end
